/**
 * Created by a1 on 16/4/29.
 */

var width = 320
var height = 480
var operator = ""
var result = 0
var dot = false
var needClear = false

$(function() {
    //var container = $("#container")
    //container.width(width)
    //container.height(height)
    //
    //var resultHeight = height * 0.15
    //var result = $("#container_result")
    //result.width(width)
    //result.height(resultHeight)
    //
    //var label = $("#result")
    //label.css("max-font-size", resultHeight)
    initClick()
})

function resultNode() {
    return $("#result")
}

function resultUpdate() {
    resultNode().text(result)
}

function initClick() {
    var buttons = $("#table_button button[value]")
    buttons.click(function() {
        var value = this.value
        //alert("value = " + value)
        if($.isNumeric(value)) {
            //alert("num = " + num)
            var num = Number(value)
            if(num >= 0 && num <= 9) {
                if(needClear) {
                    resultNode().text("0")
                    needClear = false
                }
                var param = ""
                //alert("dot = " + dot)
                if(dot) {
                    param = resultNode().text() + "." + value
                    dot = false
                }else {
                    param = resultNode().text() + value
                }
                resultNode().text(Number(param))
            }
        }else {
            if(value == "c") {
                result = 0
                resultUpdate()
            }else if(value == "negative") {
                result *= -1
                resultUpdate()
            }else if(value == "%") {
                result *= 0.01
                resultUpdate()
            }else if(value == ".") {
                var text = resultNode().text()
                //alert("index = " + text.indexOf("."))
                if(text.indexOf(".") == -1) {
                    dot = true
                }
            }else if(value == "=") {
                compute()
                operator = ""
            }else {
                if(operator != "") {
                    compute()
                }
                result = Number(resultNode().text())
                operator = value
                needClear = true
            }
        }
    })
}

function compute() {
    if(operator == "+") {
        result += Number(resultNode().text())
    }else if(operator == "-") {
        result -= Number(resultNode().text())
    }else if(operator == "*") {
        result *= Number(resultNode().text())
    }else if(operator == "/") {
        result /= Number(resultNode().text())
    }
    resultUpdate()
}